<template>

  <div>

    <!--    title="新增 | 编辑 打印文件配置"     -->
    <!--  table  -->
    <el-drawer
      :before-close="handleClose"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :show-close="false"
      :visible.sync="drawerVisible"
      :with-header="false"
      size="60%"
    >
      <el-card style="margin: 10px;height: 95vh">
        <div slot="header" style="display: flex;justify-content: space-between;align-items: center">
          <span>{{formStatusText}}打印文件配置</span>
          <div>
            <el-button
              @click="resetForm('createFormData')"
              type="warning" v-if="drawerFormStatus===1">
              {{ `清空` }}
            </el-button>

            <el-button @click="submitDrawer('createFormData')" type="success">
              {{ `完成${formStatusText}` }}
            </el-button>
          </div>
          <!--          <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>-->
        </div>

        <el-form
          :label-width="globalLabelWidth"
          :model="createdFormData" :rules="rules" ref="createFormData" style="margin: 20px;">
          <el-row :gutter="globalGutter">
            <el-col :span="12">
              <el-form-item label="文件名" prop="fileName">
                <el-input @input="fileNameChange" v-model="createdFormData.fileName">
                  <el-select @change="onChangeFileFormat"
                             clearable
                             placeholder="模板选择" slot="append"
                             style="width: 120px;" v-model="fileFormatType">
                    <el-option :value="e" v-for="e in formatType"></el-option>
                  </el-select>
                </el-input>

              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="文件编码" prop="code">
                <el-input disabled v-model="createdFormData.code"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="文件类型" prop="fileType">
                <el-select v-model="createdFormData.fileType">
                  <el-option
                    :key="item.key"
                    :label="item.label"
                    :value="item.key"
                    v-for="item in fileTypeOptions"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>


            <el-col :span="12">
              <el-form-item label="是否分割" prop="isSplit">
                <el-switch
                  active-value="True"
                  inactive-value="False"
                  v-model="createdFormData.isSplit"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="globalGutter">
            <el-col :span="12">
              <el-form-item label="需要补全的数量" prop="autoFillNum">
                <el-input-number
                  :max="999"
                  :min="0"
                  :precision="0" :step="1" size="small" v-model="createdFormData.autoFillNum"></el-input-number>
                <!--              <el-input onkeyup="this.value = this.value.replace(/[^\d.]/g,'');"-->
                <!--                        v-model.number="createdFormData.autoFillNum"></el-input>-->
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="文件最大尺寸" prop="maxSizeDetailId">
                <product-size-select :value.sync="createdFormData.maxSizeDetailId"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="globalGutter">
            <el-col :span="12">
              <el-form-item label="文件最小数" prop="minQty">
                <el-input-number
                  :max="999"
                  :min="0"
                  :precision="0" :step="1" size="small" v-model="createdFormData.minQty"></el-input-number>
                <!--              <el-input onkeyup="this.value = this.value.replace(/[^\d.]/g,'');"-->
                <!--                        v-model.number="createdFormData.minQty"></el-input>-->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="需要文件的尺寸" prop="sizeDetailId">
                <product-size-select :value.sync="createdFormData.sizeDetailId"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="globalGutter">
            <el-col :span="12">
              <el-form-item label="文件最大数" prop="maxQty">

                <el-input-number
                  :max="999"
                  :min="0"
                  :precision="0" :step="1" size="small" v-model="createdFormData.maxQty"></el-input-number>
                <!--              <el-input onkeyup="this.value = this.value.replace(/[^\d.]/g,'');"-->
                <!--                        v-model.number="createdFormData.maxQty"></el-input>-->
              </el-form-item>
            </el-col>


            <el-col :span="12">
              <el-form-item label="文件最小尺寸" prop="minSizeDetailId">
                <product-size-select :value.sync="createdFormData.minSizeDetailId"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="globalGutter">

            <el-col :span="12">
              <el-form-item label="文件数量" prop="fileNum">
                <el-input-number
                  :max="999"
                  :min="0"
                  :precision="0" :step="1" size="small" v-model="createdFormData.fileNum"></el-input-number>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
      </el-card>
    </el-drawer>

    <!--     form  > row > col > formItem > input ...     -->
    <el-alert
      :closable="false"
      show-icon
      title="打印文件配置,可以配置多个打印文件,需要排序的话直接拖拽行来排序"
      type="success"
    >
    </el-alert>

    <!--    <div class="show-d">-->
    <!--      <el-tag>The after dragging order :</el-tag>-->
    <!--      {{ newOrderList }}-->
    <!--    </div>-->

    <AzureDynamicTable
      :column-des-objs="columnDesObjs"
      :data="tableData"
      :showSeq="true"
      empty-text="暂无配置的打印文件,请点击左上角添加"
      ref="dragTable"
      row-key="fileId"
      v-loading="listLoading"
    >
      <template #tableHead>
        <a-button @click="handleAddHalfProduct" type="success">新增打印文件配置</a-button>

        <transition name="el-zoom-in-center">
          <a-button
            @click="submitChangeSort"
            type="primary" v-if="sortHasChanged">保存文件顺序
          </a-button>
        </transition>
      </template>
      <template slot="operator" slot-scope="{scope:{row,$index}}">
        <AButton @click="handleEditProduct({row,$index})" type="primary">编辑</AButton>
        <el-popconfirm
          @onConfirm="handleDeleteProduct({row,$index})"
          style="margin-left: 10px;"
          title="是否确定删除该产品？">
          <AButton slot="reference" type="danger">
            删除
          </AButton>
        </el-popconfirm>
      </template>

      <template slot="cusColWidthHeight" slot-scope="{scope:{row:{height='-',width='-'},$index}}">
        <el-tag>
          {{`宽${width} * 高${height}`}}
        </el-tag>
      </template>

    </AzureDynamicTable>

    <pagination
      :limit.sync="limit"
      :page.sync="page" :total="total"
      @pagination="getData"
      v-show="total>0"/>
  </div>
</template>

<script>

  import AButton from '@/components/ATheFridayClub/AButton'
  import AzureDynamicTable from '@/components/ATheFridayClub/mDynamicTable/AzureDynamicTable'
  import Pagination from '@/components/Pagination/index'
  import {
    PageQueryProductFile,
    ModifyProductFile,
    DeleteProductFile,
    GenerateProductFileCode
  } from '@/api/productInformation'
  import { ERR_OK } from '@/utils/commons'
  import layoutMixin from '@/mixins/layoutMixin'
  import form from '@/mixins/form'
  import ProductSizeSelect from '@/components/ATheFridayClub/businessSelect/product/productSizeSelect'
  import { objFirstKeyLowerCase } from '@/utils/fridayClub/objectUtil'
  import { deepClone } from '@/utils'
  import Sortable from 'sortablejs'
  import { debugLogger } from '@/utils/fridayClub/functianal'

  const formatType = ['*', 'fy1|扉页1|前扉页', 'fy2|扉页2|后扉页']

  const printFileFactory = ({ code, productId }) => {
    return {
      fileNum: 1,
      autoFillNum: 1,
      code,
      productId,

      fileId: null,
      fileName: '*',
      fileOrder: null,
      fileType: null,
      isSplit: 'False',
      maxQty: 1,
      maxSizeDetailId: null,
      minQty: 1,
      minSizeDetailId: null,
      productFileId: null,
      sizeDetailId: null
    }
  }

  export default {
    name: 'printFile',
    components: { ProductSizeSelect, AButton, AzureDynamicTable, Pagination },
    computed: {
      formStatusText() {
        return this.drawerFormStatus === 1 ? '新增' : '修改'
      }
    },
    data() {

      this.rules = {
        fileName: [
          { type: 'string', required: true, message: '请选输入文件名', trigger: ['change', 'blur'] }
        ],
        fileType: [
          { type: 'string', required: true, message: '请选择文件类型', trigger: ['change', 'blur'] }
        ],
        isSplit: [
          { type: 'string', required: true, message: '请选择是否切割', trigger: ['change', 'blur'] }
        ],
        maxQty: [
          { type: 'number', required: true, message: '请选输入最大数量', trigger: ['change', 'blur'] }
        ],
        minQty: [
          { type: 'number', required: true, message: '请选输入最小数量', trigger: ['change', 'blur'] }
        ],
        // code: [
        //   { type: 'number', required: true, message: '请获取产品编码', trigger: ['change', 'blur'] }
        // ],
        maxSizeDetailId: [
          { type: 'number', required: true, message: '请选择文件最小尺寸', trigger: ['change', 'blur'] }
        ],
        minSizeDetailId: [
          { type: 'number', required: true, message: '请选择文件最大尺寸', trigger: ['change', 'blur'] }
        ],
        fileNum: [
          { type: 'number', required: true, message: '请选择文件数量', trigger: ['change', 'blur'] }
        ],
        autoFillNum: [
          { type: 'number', required: true, message: '请选择文件补全数量', trigger: ['change', 'blur'] }
        ],
        sizeDetailId: [
          { type: 'number', required: true, message: '请选择需要文件的尺寸', trigger: ['change', 'blur'] }
        ]
      }
      return {
        sortHasChanged: false,
        newOrderList: [],
        drawerVisible: false,
        loading: false,
        tableData: [],
        listLoading: false,
        columnDesObjs: [
          // { key: 'fileOrder', label: '文件顺序' },
          { key: 'code', label: '产品文件编码' },
          { key: 'fileName', label: '文件名' },
          { key: 'cusColWidthHeight', label: '宽&高', width: 200 },
          { key: 'fileNum', label: '文件数量' },
          { key: 'autoFillNum', label: '需要补全的数量' },
          { key: 'fileType', label: '文件类型' },
          { key: 'isSplit', label: '是否切割', filter: v => v === 'True' ? '是' : '否', tag: true },
          { key: 'maxQty', label: '文件最大数' },
          { key: 'minQty', label: '文件最小数' },
          { key: 'productName', label: '产品名' },
          { key: 'sizeDetailId', label: '需要文件的尺寸', isDefaultShowDynamicColumn: false },
          { key: 'sizeName', label: '尺寸名' },
          { key: 'fileId', label: 'ID', isDefaultShowDynamicColumn: false },
          { key: 'sizeId', label: '尺寸ID', isDefaultShowDynamicColumn: false },
          // { key: 'Width', label: '宽（mm）' },
          // { key: 'Height', label: '高（mm）' },
          { key: 'operator', label: '操作', width: 200 }

        ],
        formatType,
        fileFormatType: '*', //  1 任意
        createdFormData: {},
        fileOrderOptions: [],
        fileTypeOptions: [
          { label: 'jpg', key: 'jpg' }
          // { label: 'pdf', key: 'pdf' }
        ],
        isSplitOptions: [
          { label: '是', key: true },
          { label: '否', key: false }
        ],
        productId: 0,
        total: 0,
        page: 1,
        limit: 10,

        drawerFormStatus: 1 //  1 新增 2 修改
      }
    },
    mixins: [layoutMixin, form],
    created() {
      // console.log(this.$route.query.ProductId,'52::::::::::')
      this.productId = this.$route.query.ProductId
      this.getData()
    },
    filters: {},
    methods: {
      fileNameChange(val) {

        console.log(val)
        console.log(formatType)
        const pos = formatType.findIndex(v => v === val)

        if (pos > -1) {
          this.fileFormatType = val
        } else {
          this.fileFormatType = '*'
        }

      },

      onChangeFileFormat(v) {
        console.log(v)
        this.createdFormData.fileName = v
      },
      handleClose(done) {
        this.$confirm('您还没有完成新增,请是否确认退出', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(_ => {
          // this.loading = true
          // this.submitDrawer()
          done()

        }).catch(_ => {
        }).finally(() => {
          this.loading = false
        })
      },

      async handleAddHalfProduct() {
        this.checkCompleteSortOperator()

        this.drawerFormStatus = 1

        const code = await this.getProductFileCode()   //  产品工厂函数
        this.createdFormData = printFileFactory({ code, productId: this.productId })
        this.clearValidate('createFormData')

        this.drawerVisible = true
      },
      handleEditProduct({ row, $index }) {
        this.checkCompleteSortOperator()

        //  drawerFormStatus
        this.createdFormData = { ...row }
        console.log(this.createdFormData)

        this.drawerFormStatus = 2
        this.drawerVisible = true

      },

      checkCompleteSortOperator(){
        if (this.sortHasChanged){
          const msg = "请先完成排序并且保存"
          this.$notify.warning({title:msg})
          throw new Error(msg)
        }
      },
      async handleDeleteProduct({ row: { fileId }, $index }) {
        this.checkCompleteSortOperator()
        try {
          const { Code, Result } = await DeleteProductFile([fileId])
          if (Code === ERR_OK) {
            this.$message.success('删除打印文件成功')
            const { [$index]: del, ...remain } = this.tableData
            this.tableData = Object.values(remain)
            const paddingList = this.tableData.slice($index).map
            (v => ({ ...v, fileOrder: v.fileOrder - 1, fileCode: v.code }))
            if (paddingList.length) {
              this.tableData.slice($index).forEach(v => v.fileOrder = v.fileOrder - 1)
              await ModifyProductFile(paddingList)
              // await this.getData()
            }
          }
        } catch (e) {
          this.$message.warning('删除打印文件失败')
        }
      },
      async submitDrawer(formName) {
        try {
          // this.checkCompleteSortOperator()

          await this.validateForm(formName)
          const { code, ...restParam } = this.createdFormData

          const params = { ...restParam, fileCode: code }

          console.log(JSON.stringify(params));

          //  新增
          if (this.drawerFormStatus === 1) {
            Object.assign(params, { fileOrder: this.tableData.length + 1 })
          }

          const { Code, Result } = await ModifyProductFile([params])
          if (Code === ERR_OK) {
            this.$message.success(`${this.formStatusText}成功！`)
            this.drawerVisible = false
            await this.getData()
          }
        } catch (e) {
          console.log(e)
        }
      },
      //查询
      async getData() {
        this.listLoading = true
        try {
          const { Code, Result } = await PageQueryProductFile({
            productId: this.productId,
            pageSize: this.limit,
            pageNum: this.page
          })
          if (Code === ERR_OK) {
            const { CurrentPage, RecordCount, Rows } = Result
            this.page = CurrentPage
            this.total = RecordCount
            this.tableData = (Rows |> objFirstKeyLowerCase)
              .sort((a, b) => a.fileOrder - b.fileOrder)

            this.newOrderList = this.tableData.map(v => v.fileOrder)
            await this.$nextTick()
            this.setSort()
          }
        } catch (e) {
          console.log(e)
        } finally {
          this.listLoading = false
        }
      },

      setSort() {
        const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
        this.sortable = Sortable.create(el, {
          ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
          animation: 150,
          setData: function(dataTransfer) {
            // to avoid Firefox bug
            // Detail see : https://github.com/RubaXa/Sortable/issues/1012
            dataTransfer.setData('Text', '')
          },
          onEnd: evt => {
            this.sortHasChanged = true
            const { oldIndex, newIndex } = evt
            console.log(oldIndex, newIndex)
            // const targetRow = this.tableData.splice(evt.oldIndex, 1)[0]
            // this.tableData.splice(evt.newIndex, 0, targetRow)

            // const oldData = this.tableData[oldIndex]
            // const newData = this.tableData[newIndex]

            // const tempOrder = newData['fileOrder']
            // newData['fileOrder'] = oldData['fileOrder']
            // oldData['fileOrder'] = tempOrder

            // this.tableData[oldIndex]['fileOrder'] = newIndex + 1
            // this.tableData.slice(oldIndex).forEach(v => v.fileOrder = v.fileOrder - 1)
            const targetRow = this.tableData.splice(evt.oldIndex, 1)[0]
            this.tableData.splice(evt.newIndex, 0, targetRow)

            const tempIndex = this.newOrderList.splice(evt.oldIndex, 1)[0]
            this.newOrderList.splice(evt.newIndex, 0, tempIndex)
          }
        })
      },

      async submitChangeSort() {
        //  sortHasChanged
        const sortDataList = this.tableData.map((v, idx) => {
          return { ...v, fileOrder: idx + 1, fileCode: v.code }
        }) |> debugLogger()

        //    { ...restParam, fileOrder: this.tableData.length + 1, fileCode: code }
        try {
          const { Code, Result } = await ModifyProductFile(sortDataList)
          if (Code === ERR_OK) {
            this.sortHasChanged = false
            this.$message.success(`修改文件顺序成功！`)
            // this.getData()
          }
        } catch (e) {
          this.$message.warning(`修改文件顺序失败！`)
          console.log(e)
        }
      },

      //获取最新文件Code
      async getProductFileCode() {
        const { Code, Result: code } = await GenerateProductFileCode()
        if (Code === ERR_OK) {
          // this.createdFormData.fileCode = Result
          return code
        }
      }

    }

  }
</script>

<style>
  .sortable-ghost {
    opacity: .8;
    color: #fff !important;
    background: #42b983 !important;
  }
</style>

<style lang="scss" scoped>

</style>
